﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

using System.IO;
using System.Xml;

using Cisoft.Cisoft3G.BLL;
using Cisoft.Cisoft3G.Model;

public partial class Business_Cisoft3G_ContactsManage_ContactsFromExcel : WebUI.Page.BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
        }

        //btnImport.Attributes.Add("onclick", "return confirm('您确定要导入数据吗？')");
    }

    #region 导入Excel
    protected void btnImport_Click(object sender, EventArgs e)
    {
        Label1.Text = "";

        if (FileUpload1.FileName != null && FileUpload1.FileName != "")
        {

            if (temCheckType(FileUpload1))
            {
                //上传文件返回服务器路径URL
                string strurl = "";
                strurl = doUpload(FileUpload1);
                if (strurl != "")
                {
                    doImport(strurl);
                    //if (doImport(strurl))
                    //{
                    //    Label1.Text = "导入成功！";

                    //    PageRight("导入成功！", "ContactsManage.aspx", "返回 ", "");
                    //}
                    //else
                    //{
                    //    Label1.Text = "导入失败！";

                    //    PageError("导入失败！", "ContactsManage.aspx", "返回重试或联系管理员 ", "");

                    //}
                }
                else
                {
                    //Label1.Text = "导入文件过程中上传异常！";
                    PageError(ModalPopupExtender2, lblTS, btnConfirm2, "<h4>导入文件过程中上传异常</h4>");
                    return;
                }
            }
            else
            {
                //Label1.Text = "导入文件类型不对！";
                PageError(ModalPopupExtender2, lblTS, btnConfirm2, "<h4>导入文件类型不对！</h4>");
                return;
            }
        }
        else
        {
            //Label1.Text = "请选择导入的文件";
            PageError(ModalPopupExtender2, lblTS, btnConfirm2, "<h4>请选择导入的文件</h4>");
            return;
        }
    }
    #endregion

    #region 导入逻辑
    public void doImport(string url)
    {
        ContactsBO bll = new ContactsBO();
        bool result = false;

        ImportBO blldataset = new ImportBO();
        DataSet ds = new DataSet();

        #region  
        ds = blldataset.GetDataSetBySqlExcel(url, "select * from [通讯录信息$]");

        if (ds.Tables[0].Rows.Count > 0)
        {
            int all = 0;
            int ok = 0;
            int wrong = 0;

            all = ds.Tables[0].Rows.Count;
            //从第一行开始
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                DataSet dsishave = new DataSet();
                //检查单位名称是否已存在
                //dsishave = bllEnterprise.GetListAnyWhere(" EI_Name='" + ds.Tables[0].Rows[i]["单位全称"] + "'");
                //dsishave = bll.GetList(" CT_Name='" + ds.Tables[0].Rows[i]["姓名"].ToString().Trim() +
                //    "' and CT_Mobile='" + ds.Tables[0].Rows[i]["手机号码"].ToString().Trim() + "' ");
                dsishave = bll.GetList(" 1=1 " + 
                    " and CT_Mobile='" + ds.Tables[0].Rows[i]["手机号码"].ToString().Trim() + "' ");
                if (dsishave.Tables[0].Rows.Count > 0)
                {
                    show("联系人：" + ds.Tables[0].Rows[i]["姓名"].ToString() + "的手机号码" + ds.Tables[0].Rows[i]["手机号码"].ToString().Trim() + "存在重复记录，不做导入！");
                    wrong++;
                    continue;
                }
                else
                {
                    ContactsMO model = new ContactsMO();
                    try
                    {
                        model.CT_ContactID = bll.GetMaxId();
                        model.CT_Address = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["地址"].ToString())?"":ds.Tables[0].Rows[i]["地址"].ToString();
                        model.CT_Company = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["单位"].ToString()) ? "" : ds.Tables[0].Rows[i]["单位"].ToString();
                        model.CT_CompanyAddress = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["单位地址"].ToString()) ? "" : ds.Tables[0].Rows[i]["单位地址"].ToString();
                        model.CT_Department = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["部门"].ToString()) ? "" : ds.Tables[0].Rows[i]["部门"].ToString();
                        model.CT_Duty = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["职务"].ToString()) ? "" : ds.Tables[0].Rows[i]["职务"].ToString();
                        model.CT_Email = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["电子邮箱"].ToString()) ? "" : ds.Tables[0].Rows[i]["电子邮箱"].ToString();
                        //model.CT_Mobile = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["手机号码"].ToString()) ? "" : ds.Tables[0].Rows[i]["手机号码"].ToString();
                        model.CT_Name = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["姓名"].ToString()) ? "" : ds.Tables[0].Rows[i]["姓名"].ToString();
                        model.CT_Phone = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["电话号码"].ToString()) ? "" : ds.Tables[0].Rows[i]["电话号码"].ToString();
                        model.CT_PostCode = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["邮政编码"].ToString()) ? "" : ds.Tables[0].Rows[i]["邮政编码"].ToString();
                        model.CT_QQ = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["QQ号码"].ToString()) ? "" : ds.Tables[0].Rows[i]["QQ号码"].ToString();
                        model.CT_Sex = ds.Tables[0].Rows[i]["性别"].ToString() == "男" ? 1 : 0;
                        model.CT_Mobile2 = string.IsNullOrEmpty(ds.Tables[0].Rows[i]["第二手机号码"].ToString()) ? "" : ds.Tables[0].Rows[i]["第二手机号码"].ToString();

                       // Cisoft.Cisoft3G.Model.ContactGroupMO cgMO = new Cisoft.Cisoft3G.BLL.ContactGroupBO().GetModel(" CG_GroupName = '" +
                       //     ds.Tables[0].Rows[i]["通讯录组"].ToString() + "' ");
                       // model.CG_ContactGroupID_FK = cgMO == null ? 0 : cgMO.CG_ContactGroupID;
                    }
                    catch (Exception ex)
                    {
                        show(ex.Message);
                        wrong++;
                        continue;
                    }

                    //手机号码验证
                    Regex reg = new Regex(@"^15[0-9]{1}\d{8}|13\d{9}|18[6789]{1}\d{8}$");
                    if (reg.IsMatch(ds.Tables[0].Rows[i]["手机号码"].ToString()))
                    {
                        model.CT_Mobile = ds.Tables[0].Rows[i]["手机号码"].ToString();
                    }
                    else
                    {
                        show("联系人：" + model.CT_Name +" 的手机号码不是有效的手机号码！");
                        wrong++;
                        continue;
                    }
                    //通讯录组验证
                    bool groupIsExsist = false;
                    int groupid = -1;
                    DataTable dt = new ContactGroupBO().GetAllList().Tables[0];
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["CG_GroupName"].ToString() == ds.Tables[0].Rows[i]["通讯录组"].ToString())
                        {
                            groupIsExsist = true;
                            groupid = int.Parse(row[0].ToString());
                            break;
                        }
                    }
                    if (groupIsExsist)
                    {
                        model.CG_ContactGroupID_FK = groupid;
                    }
                    else
                    {
                        show("联系人：" + model.CT_Name + " 的通讯录组不存在！");
                        wrong++;
                        continue;
                    }


                    //插入通讯录表
                    if (model != null)
                    {
                        try
                        {
                            int j = bll.AddWithResult(model);
                            //添加至管理员表
                            AddToUserTable(model.CT_Mobile, model.CT_Name);

                            ok += j > 0 ? j : 0;
                        }
                        catch (Exception ex)
                        {
                            wrong++;
                            show(ex.Message);
                            continue;
                        }
                    }
                }
                
            }
            Label1.Text = "导入完成！一共需导入" + all + "条，成功" + ok + "条，失败" + wrong + "条！";
        }
        
        #endregion
        //return result;
    }
    #endregion

    #region 导入检查
    public bool temCheckType(FileUpload inputfile)
    {
        bool result = false;
        string filename = inputfile.FileName;


        if (filename.LastIndexOf(".") > 0)
        {
            string exname = filename.Substring(filename.LastIndexOf(".") + 1, filename.Length - filename.LastIndexOf(".") - 1);

            exname = System.IO.Path.GetExtension(inputfile.FileName);

            if (exname == ".xls")
            {
                result = true;
                return result;
            }
            else
            {
                return result;
            }
        }

        return result;
    }
    #endregion

    #region 输出
    private void show(string str)
    {
        Label2.Text +=("<span style='color:white;'>" + str + "</span> <br/>");
    }
    #endregion

    #region 全为数字 public bool isnumber(string s)
    /// <summary>
    /// 全为数字 
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public bool isnumber(string s)
    {
        int Flag = 0;
        char[] str = s.ToCharArray();
        for (int i = 0; i < str.Length; i++)
        {
            if (Char.IsNumber(str[i]))
            {
                Flag++;
            }
            else
            {
                Flag = -1;
                break;
            }
        }
        if (Flag > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    #endregion

    #region 上传文件返回服务器URL
    public string doUpload(FileUpload FileUploadModel)
    {
        string strResult = "";
        if (FileUploadModel.PostedFile.FileName.Trim() != "")
        {
            String fileName = FileUploadModel.PostedFile.FileName.Substring(FileUploadModel.PostedFile.FileName.LastIndexOf("\\") + 1, FileUploadModel.PostedFile.FileName.Length - 1 - FileUploadModel.PostedFile.FileName.LastIndexOf("\\"));
            //取到当前时间的年、月、日、分、秒和毫秒的值,并使用字符串格式把它们组合成一个字符串

            String fileTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()

            + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()

            + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()

            + DateTime.Now.Millisecond.ToString();

            //在时间字符串后面添加一个随机数和文件的后缀名

            String src = fileName.Substring(fileName.LastIndexOf(".") + 1, fileName.Length - fileName.LastIndexOf(".") - 1).ToLower();

            //后缀名限制
            //if (src.ToLower() == "rar" || src.ToLower() == "doc" || src.ToLower() == "xls")


            fileName = fileTime + GetRandomint(10000) + "." + src;

            ///上载文件到服务器硬盘

            try
            {

                FileUploadModel.PostedFile.SaveAs(Server.MapPath(Request.ApplicationPath) + "\\uploads\\Contact\\" + fileName);
                strResult = Server.MapPath(Request.ApplicationPath) + "\\uploads\\Contact\\" + fileName;
            }
            catch (Exception ex)
            {
                return strResult;
            }


        }
        return strResult;

    }
    #endregion

    #region 默认产生一个小于10000的随机正整数
    private String GetRandomint(int nLimit)
    {
        int n = 10000;
        if (nLimit > 0)
        {
            n = nLimit;
        }
        Random random = new Random();
        //默认产生一个小于10000的随机正整数
        return (random.Next(n).ToString());
    }
    #endregion

    #region 新增至管理员表
    private void AddToUserTable(string mobile, string realname)
    {
        string xmlPath = Server.MapPath(Request.ApplicationPath + "/xmlconfig/sys/cis.config");
        string roleid = Cisoft.IntegrationSystem.Common.XMLHelper.GetConfigValue("cisDefaultMemberRole", xmlPath);

        Cisoft.IntegrationSystem.BLL.UserBO userBll = new Cisoft.IntegrationSystem.BLL.UserBO();
        Cisoft.IntegrationSystem.Model.UserMO userModel = new Cisoft.IntegrationSystem.Model.UserMO();
        Cisoft.IntegrationSystem.BLL.UserInfoBO uiBll = new Cisoft.IntegrationSystem.BLL.UserInfoBO();
        Cisoft.IntegrationSystem.Model.UserInfoMO uiModel = new Cisoft.IntegrationSystem.Model.UserInfoMO();

        int id = userBll.GetMaxID();
        userModel.UserID = id;
        userModel.UserGroupID = 0;
        userModel.UserName = string.Format("CG_{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
        userModel.UserPassword = new Cisoft.IntegrationSystem.Common.MD5().HashString("123456");
        userModel.UserRealName = realname;
        userModel.Userrole = int.Parse(roleid);
        userModel.UserApplyDate = DateTime.Now;

        uiModel.UI_UserID_FK = id;
        uiModel.UI_JoblName = "";
        uiModel.UI_Phone = mobile;

        try
        {
            userBll.AddRecord(userModel);
            uiBll.Add(uiModel);
        }
        catch (Exception ex)
        {

            throw;
        }
    }
    #endregion
}
